<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.build" placeholder="请选择车位类型" style="width: 140px;margin-right: 10px;" class="filter-item" @change="handleFilter">
        <el-option v-for="(item, index) in carType" :key="`${item.key}${index}`" :label="item.label" :value="item.key" />
      </el-select>
      <!-- <el-select v-model="listQuery.floor" placeholder="请选择楼层" style="width: 140px;margin-right: 10px;" class="filter-item" @change="handleFilter">
        <el-option v-for="item in floor" :key="item" :label="item" :value="item" />
      </el-select> -->
      <el-input v-model="listQuery.phone" placeholder="车位编码" style="width: 200px;margin-right: 10px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索 
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增车位
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导入
      </el-button> -->
      <!-- <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <!-- 楼栋-楼层-房间号 前端拼 -->
      <el-table-column label="车位名称" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车位编号" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
          <el-tag>{{ row.author }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="车位类型" width="80px">
        <template slot-scope="{row}">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车位状态" width="80px">
        <template slot-scope="{row}">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否有充电桩" width="80px">
        <template slot-scope="{row}">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="充电桩数量" width="80px">
        <template slot-scope="{row}">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button style="margin-right: 10px;" size="mini" @click="handleDetail(row)">
            详情
          </el-button>
          <el-popover
            placement="right"
            width="100"
            trigger="click">
            <div>
              <div class="pop-btn" @click="handleSale(row)">车位出售</div>
              <div class="pop-btn" @click="handleRentOut(row)">车位租赁</div>
              <div class="pop-btn" @click="handleChargingPile(row)">添加充电桩</div>
              <div class="pop-btn" @click="handleUpdate(row)">编辑</div>
              <div class="pop-btn" @click="handleDetail(row)">详情</div>
              <div class="pop-btn" @click="handleDelete(row,$index)">删除</div>
            </div>
            <i slot="reference" class="el-icon-more" style="cursor: pointer;"></i>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <div v-if="['update', 'create', 'detail'].includes(dialogStatus)">
          <el-form-item label="车位名称" prop="parkingName">
            <el-input placeholder="请输入车位名称"  :disabled="isDetail" v-model="temp.parkingName" />
          </el-form-item>
          <el-form-item label="车位编号" prop="parkingCode">
            <el-input placeholder="请输入车位编号"  :disabled="isDetail" v-model="temp.parkingCode" />
          </el-form-item>
          <el-form-item label="车位类型" prop="parkingType">
            <el-select :disabled="isDetail" v-model="temp.parkingType" style="width: 290px"  placeholder="请选择楼层" class="filter-item" @change="handleFilter">
              <el-option v-for="item in carType" :key="item.label" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否有充电桩" prop="hasChargingStation">
            <el-select :disabled="isDetail" v-model="temp.hasChargingStation" style="width: 290px"  placeholder="请选择楼层" class="filter-item" @change="handleFilter">
              <el-option v-for="item in yesOrNot" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="+temp.hasChargingStation === 1" label="充电桩数量" prop="chargingStationNum">
            <el-input :disabled="isDetail" v-model="temp.chargingStationNum"/>
          </el-form-item>
          <el-form-item label="月租金" prop="monthlyRent">
            <el-select :disabled="isDetail" v-model="temp.monthlyRent" style="width: 290px"  class="filter-item" placeholder="请选择房屋状态">
              <el-option v-for="item in houseStatus" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="车位状态" prop="parkingStatus">
            <el-select :disabled="isDetail" v-model="temp.parkingStatus" style="width: 290px"  placeholder="请选择楼层" class="filter-item" @change="handleFilter">
              <el-option v-for="item in floor" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="已缴纳车位费" prop="paidFees">
            <el-input :disabled="isDetail" v-model="temp.paidFees" />
          </el-form-item>
          <el-form-item label="剩余车位费" prop="remainingCost">
            <el-input :disabled="isDetail" v-model="temp.remainingCost" />
          </el-form-item>
          <!-- <el-form-item label="车位总费用" prop="title">
            <el-input :disabled="isDetail" v-model="temp.title" />
          </el-form-item> -->
          <el-form-item label="售价" prop="salePrice">
            <el-input placeholder="请输入售价"  :disabled="isDetail" v-model="temp.salePrice" />
          </el-form-item>
        </div>
        <el-form-item v-if="dialogStatus === 'chargingPile'" label="充电桩数量" prop="chargingStationNum">
          <el-input-number v-model="temp.chargingStationNum" :precision="0" :step="1" :min="1" :max="10"></el-input-number>
        </el-form-item>
        <div v-if="dialogStatus === 'sale' || dialogStatus === 'rentOut'">
        <el-form-item label="交易用户" prop="chargingStationNum">
          <el-select :disabled="isDetail" v-model="temp.parkingStatus" style="width: 290px"  placeholder="请选择购买用户" class="filter-item" @change="handleFilter">
            <el-option v-for="item in floor" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <!-- 默认租一年 -->
        <el-form-item  v-if="dialogStatus === 'rentOut'" label="租赁时间" prop="saleTime">
          <div style="display: flex;">
            <el-date-picker
              v-model="temp.saleTime"
              type="monthrange"
              range-separator="至"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              :picker-options="pickerOptions"
              format="yyyy 年 MM 月"
              value-format="timestamp"
              @change="timeChange">
          </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="车位编号" prop="salePrice">
          <el-input placeholder="请输入售价"  :disabled="true" v-model="temp.salePrice" />
        </el-form-item>
        <el-form-item label="车位类型" prop="salePrice">
          <el-input placeholder="请输入售价" :disabled="true" v-model="temp.salePrice" />
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'rentOut'" label="月租金" prop="monthlyRent">
          <el-input placeholder="请输月租金"  v-model="temp.monthlyRent" />
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'rentOut'" label="总费用" prop="allPrice">
          <el-input placeholder="请输总费用"  :disabled="true" v-model="temp.allPrice" />
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'sale'" label="售价" prop="salePrice">
          <el-input placeholder="请输入售价"  :disabled="true" v-model="temp.salePrice" />
        </el-form-item>
      </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button v-if="dialogStatus!=='detail'" type="primary" @click="handleSure">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchPv, cfreateArticle, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import {carType, floor, build, houseStatus, yesOrNot} from '@/utils/dic-data'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'Cars',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一年',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setMonth(start.getMonth() - 12);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setMonth(start.getMonth() - 6);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      startMonth: null, // 开始月份
      endMonth: null, // 结束月份
      saleMonth: 1,
      build,
      floor,
      carType, 
      yesOrNot,
      isDetail: false,
      houseStatus,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        phone: undefined,
        // type: undefined,
        // sort: '+id'
        build: '1栋',
        floor: '1层'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      // sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      // statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        salePrice: 0, // 车位出售费用
        remainingCost: 0, //剩余车位费
        parkingType: '', // 车位类型
        parkingName: '', // 车位名称
        parkingStatus: 0,// 车位状态 0、闲置；1、已出租；2、已出售; 3、已预定 ,
        parkingCode: '', // 车位编码
        paidFees: '',// 已缴纳车位费
        monthlyRent: 210, // 月租金
        houseHoldId: '', // 所属用户
        hasChargingStation: 0, // 0 无
        chargingStationNum: 1,
        saleTime: [],
        allPrice: 0, // 总费用租车
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑车位',
        create: '新增车位',
        detail: '车位详情',
        chargingPile: '添加充电桩',
        sale: '车位出售',
        rentOut: '车位出租'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        parkingName: [{ required: true, message: '请输入车位名称', trigger: 'blur' }],
        parkingCode: [{ required: true, message: '请输入车位编号', trigger: 'blur' }],
        parkingType: [{ required: true, message: '请选择车位类型', trigger: 'blur' }],
        hasChargingStation: [{ required: true, message: '请选择是否有充电桩', trigger: 'blur' }],
        chargingStationNum: [{ required: true, message: '请输入充电桩数量', trigger: 'blur' }],
        monthlyRent: [{ required: true, message: '请输入月租金', trigger: 'blur' }],
        parkingStatus: [{ required: true, message: '请选择车位状态', trigger: 'blur' }],
        paidFees: [{ required: true, message: '请输入已缴纳车位费', trigger: 'blur' }],
        remainingCost: [{ required: true, message: '请输入剩余车位费', trigger: 'blur' }],
        salePrice: [{ required: true, message: '请输入售价', trigger: 'blur' }],
        saleTime: [{ required: true, message: '请选择租赁时间', trigger: 'change' }],
      },
      downloadLoading: false
    }
  },
  created() {
    let date = new Date()
    console.log(date.setMonth(date.getMonth() - 12))
    let start = date.setMonth(date.getMonth() - 12);
    this.temp.time = [start, date]
    // 
    this.getList()
  },
  methods: {
    timeChange (val) {
      // 一小时的时间戳: 3,600,000: 一天的时间戳: 86400000: 一个月的时间戳: 2592000000: 一年的时间戳: 31104000000
      this.saleMonth = Math.floor((val[1]-val[0])/2592000000)
      this.temp.allPrice = (Number(this.temp.monthlyRent * this.saleMonth)).toFixed(2)
    },
    handleSure () {
      switch (this.dialogStatus) {
        case "create":
          this.createData()
        break;
        case "update":
          this.updateData()
        break;
        case "chargingPile":
          this.updateChargingPile()
        break;
        case "sale":
          this.carSale()
        break;
        case "rentOut":
          this.carRentOut()
        break;
      }
    },
    // 更新充电桩
    updateChargingPile () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          alert(1)
        }
      })
    },
    // 车位出售
    carSale () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
        }
      })
    },
    // 车位出租
    carRentOut () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
        }
      })
    },
    // 添加充电桩
    handleChargingPile () {
      this.resetTemp()
      this.dialogStatus = 'chargingPile'
      this.dialogFormVisible = true
      this.isDetail =  false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 出售
    handleSale () {
      this.resetTemp()
      this.dialogStatus = 'sale'
      this.dialogFormVisible = true
      this.isDetail =  false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 出租
    handleRentOut () {
      this.resetTemp()
      this.dialogStatus = 'rentOut'
      this.dialogFormVisible = true
      this.isDetail =  false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    // 新增
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.isDetail =  false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 详情
    handleDetail () {
      this.resetTemp()
      this.dialogStatus = 'detail'
      this.dialogFormVisible = true
      this.isDetail =  true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.isDetail =  false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style scoped>
  .pop-btn {
    height: 45px;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    width: 100%;
    cursor: pointer;
  }
</style>
